<?php

namespace Biz\model\advertisement;


use Doraemon\tools\Log;

class MTaskRecord extends MBaseDbModel
{
    const _CONFIG_FILE_ = 'db_position';

    const _CONFIG_SELECT_ = 'db_position';

    const _DATABASE_ = 'hhz_position';

    const _TABLE_NAME = 'task_record';

    const STATUS_WAIT = 1;
    const STATUS_COMPLETE = 2;
    const STATUS_LIVING = 3;
    const STATUS_CLOSE = 4;

    protected $task = null;

    public function __construct($task = null)
    {
        if ($task) $this->task = $task;
    }

    public function __destruct()
    {
        Log::position_info('record', $this->task);
        $final = 0;
        $exec = 0;
        $error = [];
        foreach ($this->task as $k => $item) {
            try {
                if (is_callable($item)) call_user_func(...$item);
            } catch (\Exception $e) {
                $error[] = $e->getMessage();
            }
        }

        self::create(['final' => $final, 'exec' => $exec, 'task_error' => json_encode($error, JSON_UNESCAPED_UNICODE)]);
    }

    public static function record($task)
    {
        new self($task);
    }

    public static function allWaitTask($size = 10000): array
    {
        $all = [];
        $p = 0;
        while (true) {
            $where = ['status' => self::STATUS_WAIT, 'LIMIT' => [$p * $size, $size]];
            $list = self::select('*', $where);
            if (empty($list)) break;
            $p ++;
            $all = array_merge($all, $list);
        }
        return $all;
    }


    public static function create($data)
    {
        $time = time();
        $insertData = [
            'final' => $data['final'],
            'exec' => $data['exec'],
            'v' => 1,
            'task_error' => $data['task_error'],
            'status' => self::STATUS_WAIT,
            'addtime' => $time,
            'edittime' => $time,

        ];
        return self::insert($insertData)->rowCount() ? self::id() : false;
    }

    public static function modify($id, $data)
    {
        $data['edittime'] = time();
        $data['v[+]'] = 1;
        self::update($data, ['id' => $id]);
    }
}